import json
import time

from bs4 import BeautifulSoup
from requests import request
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pynput.keyboard import Key, Controller as c2
from pynput.mouse import Button, Controller as c1
from seleniumrequests import Chrome


# 初始化浏览器
def InitialBrowser():
    # 驱动器地址
    f = r'E:\tool\other\chorme\chromedriver.exe'
    # chrome_options 初始化选项
    chrome_options = webdriver.ChromeOptions()
    # 设置浏览器初始 位置x,y & 宽高x,y
    chrome_options.add_argument(f'--window-position={0},{0}')
    chrome_options.add_argument(f'--window-size={1200},{1000}')
    # 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
    # window.navigator.webdriver还是返回True,当返回undefined时应该才可行。
    chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
    # 关闭开发者模式
    chrome_options.add_experimental_option("useAutomationExtension", False)
    # 禁止图片加载
    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    # 设置中文
    chrome_options.add_argument('lang=zh_CN.UTF-8')
    # 更换头部
    chrome_options.add_argument(
        'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')
    # 隐藏浏览器
    # chrome_options.add_argument('--headless')  # 隐藏浏览器
    # 部署项目在linux时，其驱动会要求这个参数
    chrome_options.add_argument('--no-sandbox')
    # chrome_options.add_argument("--user-data-dir=userdir")
    # 创建浏览器对象
    driver = webdriver.Chrome(f, options=chrome_options)
    # 设置执行js代码转换模式
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
    })
    # 打开网站 测试
    # driver.get('https://www.baidu.com/')
    return driver


# 滑块验证并自动登录
def autoLogin():
    driver = InitialBrowser()
    mouse = c1()
    url = 'https://passport.tujia.com/PortalSite/LoginPage/?originUrl=https%3A%2F%2Fwww.tujia.com%2F'
    driver.get(url)
    # driver.maximize_window()
    wait = WebDriverWait(driver, 10)
    driver.get(url)
    time.sleep(3)
    driver.refresh()
    # 滑动次数超过10次自动失败
    click = 0
    while True:
        # pyautogui.press('f5')
        # keyboard.press(Key.f5)
        # driver.refresh()
        time.sleep(2)
        # mouse.position = (980, 550)
        mouse.position = (320, 550)
        time.sleep(1)
        mouse.press(Button.left)
        mouse.move(400, 2)
        time.sleep(1)
        mouse.release(Button.left)
        time.sleep(2)
        WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME, 'nc-lang-cnt')))
        click += 1
        if click > 10 or driver.find_element_by_class_name('nc-lang-cnt').text == '验证通过':
            break

    time.sleep(2)
    element = driver.find_elements_by_tag_name("div>input")
    key = 0
    for i in element:
        if key == 0:
            time.sleep(1)
            i.send_keys(18510781868)
        if key == 1:
            time.sleep(1)
            i.send_keys("wc121369")

        # print(i.get_attribute("placeholder"))
        key += 1

    submit_button = driver.find_element_by_class_name("submit")
    submit_button.click()
    # user_name = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'userInfo')))
    # print(user_name)
    # cookies = driver.get_cookies()  # Selenium为我们提供了get_cookies来获取登录cookies
    # print(cookies)

    # time.sleep(2)
    # url = "https://www.tujia.com/feapi/whitebase/flagrate"
    # driver.get(url)
    # cookies = driver.get_cookies()
    # print(cookies)

    # time.sleep(2)
    # url = "https://guanjia.tujia.com/feapi/bapi/bingo/b/pc/config/getCommonConfigs"
    # driver.get(url)
    # cookies = driver.get_cookies()
    # print(cookies)

    # time.sleep(2)
    # url = "https://guanjia.tujia.com/storemanagement/unitlist"
    # driver.get(url)
    # cookies = driver.get_cookies()
    # print(cookies)
    return driver


def getCookie():
    driver = autoLogin()
    cookies = driver.get_cookies()  # Selenium为我们提供了get_cookies来获取登录cookies
    print(cookies)

    time.sleep(2)
    url = "https://guanjia.tujia.com/storemanagement/unitlist"
    driver.get(url)
    time.sleep(2)
    cookies = driver.get_cookies()
    with open("../tmp_file/cookies06.txt", "w") as fp:
        json.dump(cookies, fp)

    print(cookies)
    time.sleep(6)
    driver.close()
    return cookies


def getCookieJs():
    driver = autoLogin()
    time.sleep(2)
    url = "https://guanjia.tujia.com/storemanagement/unitlist"
    driver.get(url)
    cookies = driver.execute_script("return document.cookie")
    print(cookies)
    return cookies


def test():
    mouse = c1()
    url = 'https://passport.tujia.com/PortalSite/LoginPage/?originUrl=https%3A%2F%2Fwww.tujia.com%2F'
    options = webdriver.ChromeOptions()
    # 不加载图片,加快访问速度
    options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
    # 此步骤很重要，设置为开发者模式，防止被各大网站识别出来使用了Selenium
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 添加本地代理
    # options.add_argument("--proxy--server=127.0.0.1:8080")
    # 添加UA
    ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
    options.add_argument('user-agent=' + ua)

    driver = webdriver.Chrome(executable_path="E:\\tool\other\chorme\chromedriver.exe", options=options)
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
    })
    driver.maximize_window()
    wait = WebDriverWait(driver, 10)
    driver.get(url)
    time.sleep(3)
    driver.refresh()
    # 滑动次数超过10次自动失败
    click = 0
    while True:
        # pyautogui.press('f5')
        # keyboard.press(Key.f5)
        # driver.refresh()
        time.sleep(2)
        mouse.position = (1562, 355)
        mouse.press(Button.left)
        mouse.move(1890, 358)
        mouse.release(Button.left)
        time.sleep(2)
        WebDriverWait(driver, 5, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME, 'nc-lang-cnt')))
        click += 1
        if click > 10 or driver.find_element_by_class_name('nc-lang-cnt').text == '验证通过':
            break

    time.sleep(2)
    element = driver.find_elements_by_tag_name("div>input")
    key = 0
    for i in element:
        if key == 0:
            time.sleep(1)
            i.send_keys(15347126062)
        if key == 1:
            time.sleep(1)
            i.send_keys(123456)

        # print(i.get_attribute("placeholder"))
        key += 1

    submit_button = driver.find_element_by_class_name("submit")
    submit_button.click()
    # user_name = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'userInfo')))
    # print(user_name)
    cookies = driver.get_cookies()  # Selenium为我们提供了get_cookies来获取登录cookies
    print(cookies)
    # driver.quit()


# webdriver
def getData():
    driver = InitialBrowser()
    # url = "http://ms.com/api/index/index"
    url = "https://guanjia.tujia.com/feapi/merchantcrm/merchant-web/v2/pc/house/pageHouseInfo"
    # driver.get(url)
    # html = driver.page_source
    # soup = BeautifulSoup(html, 'lxml')
    # cc = soup.find('body')
    # print(cc)
    # res = json.loads(cc.text)
    # print(res)
    webdriver = Chrome()
    response = webdriver.request("post", url)
    res = response.json()
    print(type(res))
    # print(res['code'])


# request尝试
def getDataOne():
    url = "https://guanjia.tujia.com/feapi/merchantcrm/merchant-web/v2/pc/house/pageHouseInfo"
    response = request("post", url)
    res = response.text
    print(res)


# 保存cookies
def saveCookie():
    cookies = getCookie()
    with open("../tmp_file/cookies06.txt", "w") as fp:
        json.dump(cookies, fp)

# 读取cookies 用request请求
def readCookie():
    url = "https://guanjia.tujia.com/feapi/merchantcrm/merchant-web/v2/pc/house/pageHouseInfo"
    cookies_dict = dict()
    strCookie = ""
    with open("../tmp_file/cookies_18510781868.txt", "r") as fp:
        cookies = json.load(fp)
        for cookie in cookies:
            cookies_dict[cookie['name']] = cookie['value']
            tmp = cookie['name'] + "=" + cookie['value']
            strCookie += tmp + ";"

    print(strCookie.rstrip(";"))
    # res = request("post", url, cookies=cookies_dict)
    # print(res.cookies.get_dict())

    # print(res.text)


# 模拟浏览器点击页面按钮并获取指定页面数据 --页面css隐藏的数据打印不出来
def getHtml():
    driver = autoLogin()
    # driver = InitialBrowser()
    # driver.get("http://tp5.com/index/index/tujia")
    time.sleep(2)
    driver.find_element_by_css_selector("div.tools-item>a").click()
    time.sleep(1)
    driver.refresh()
    time.sleep(5)
    driver.find_element_by_css_selector("a.m-menu-item:nth-child(1)").click()
    time.sleep(3)
    print(driver.page_source)
    # time.sleep(3)
    # res = driver.find_element_by_css_selector("div.layui-tab-item:nth-child(2)")
    # print(res.text)
    # time.sleep(2)
    # print(driver.page_source)
    # print("-----------------")
    # time.sleep(2)
    # res.click()
    # time.sleep(2)
    # print(driver.find_elements_by_css_selector("ul.layui-tab-title"))


def jsCookie():
    driver = InitialBrowser()
    driver.get("http://tp5.com/")
    time.sleep(2)
    str = driver.execute_script("return document.cookie")
    print(str)

    cookies = driver.get_cookies()
    print(cookies)


def getDiffArr():
    with open("../tmp_file/cookies_true.txt", "r") as fp:
        cookies_true = fp.read()

    with open("../tmp_file/cookies_mer.txt", "r") as fp:
        cookies_mer = fp.read()

    cookies_mer_arr = cookies_mer.split(";")
    cookies_true_arr = cookies_true.split(";")

    cookie_true = []
    for i in cookies_true_arr:
        cookie_true.append(i.split("=")[0])

    cookie_mer = []
    for i in cookies_mer_arr:
        cookie_mer.append(i.split("=")[0])

    diff = []
    for x in cookie_true:
        if cookie_mer.count(x) == 0:
            diff.append(x)

    print(diff)


def getHeader():
    # driver = InitialBrowser()
    # driver.get("http://tp5.com/")
    # time.sleep(1)
    driver = autoLogin()
    url = "https://guanjia.tujia.com/storemanagement/unitlist"
    driver.get(url)
    time.sleep(2)
    info = driver.execute_script("return navigator.Sec-Fetch-Dest")
    # info2 = driver.execute_script("return navigator.LL-INFO")
    # info3 = driver.execute_script("return navigator.X-TJH")
    print(info)
    # print(info2)
    # print(info3)


class vcg_get_cookies:
    pass


if __name__ == "__main__":
    t = vcg_get_cookies()
    # getCookie()
    # getData()
    # getDataOne()
    # saveCookie()
    # readCookie()
    getHtml()
    # getDiffArr()
    # jsCookie()
    # getCookieJs()
    # getHeader()
